package net.adetech.port.job;

import net.adetech.port.entity.PCGTicket;
import net.adetech.port.service.ISyncService;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Configurable
@EnableScheduling
public class SyncJob {
    @Autowired
    private ISyncService syncService;

    public static String filepath = "c:\\";
    public static  String ftpIp = "221.0.90.52";
    public static  int ftpPort = 21;
    public static  String ftpUser = "cdg";
    public static  String ftpPassword = "cdg2016";
    public static int interval=60;
    private static long lastTime = 0;

    public static String localActiveMode = "true";


    private static List<String> failedFileList = new ArrayList<String>();

    @Scheduled(cron = "0/2 * * * * *")
    public void scanFailed()
    {
        if (failedFileList.size()>0)
        {
            String fileName = failedFileList.get(0);
            failedFileList.remove(fileName);
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            System.out.println(time+"\t-->  重新发送文件："+fileName);
            upload(fileName);
        }
    }



    @Scheduled(cron = "0/2 * * * * *")
    public void sync()
    {

        long now = new Date().getTime();
        if (now - lastTime + 900> interval*1000){
            lastTime = now;
        }
        else {
            return;
        }


        List<PCGTicket> ticketList = syncService.getPcgTicketList();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if (ticketList!=null&&ticketList.size()>0)
        {
            String fileName =  saveTicketListToFile(ticketList);
            upload(fileName);
            System.out.println(time+"\t-->  上传文件："+fileName+"，记录条数："+ticketList.size());
        }
        else {
            System.out.println(time+"\t-->  无最新数据");
        }
    }

    private String saveTicketListToFile(List<PCGTicket> ticketList)
    {
        String fileName = "SH_GK_SPXX"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xml";
        if (ticketList!=null&&ticketList.size()>0)
        {

            Element rootElement = DocumentHelper.createElement("recordset");
            Document document = DocumentHelper.createDocument(rootElement);
            for (PCGTicket ticket:ticketList) {
                Element ticketElement = rootElement.addElement("R1");
                ticketElement.addElement("系统主键").addText(ticket.getId());
                ticketElement.addElement("旅客名称").addText(ticket.getXm());
                ticketElement.addElement("证件号码").addText(ticket.getSfzh());
                ticketElement.addElement("离港时间").addText(ticket.getKcsjString());
                ticketElement.addElement("班次").addText(ticket.getBc());
                ticketElement.addElement("仓位").addText(ticket.getCw());
                ticketElement.addElement("始发港").addText(ticket.getSfg());
                ticketElement.addElement("到达港").addText(ticket.getDdg());
                ticketElement.addElement("售票方式");
                ticketElement.addElement("购票时间").addText(ticket.getSpsjString());
                ticketElement.addElement("货物类型");
                ticketElement.addElement("货物重量");
                ticketElement.addElement("入库时间").addText(ticket.getRksjString());
                ticketElement.addElement("更新时间").addText(ticket.getGxsjString());
            }

            XMLWriter out = null;
            try {
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("GBK");
                out = new XMLWriter(format);
                out.setOutputStream(new FileOutputStream(filepath+fileName));
                out.write(document);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if (out!=null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return fileName;
    }


    private void upload(String fileName)
    {
        FTPClient ftp = new FTPClient();
        InputStream local=null;
        try {
            //连接ftp服务器
            ftp.connect(ftpIp, ftpPort);
            ftp.login(ftpUser, ftpPassword);

            if("true".equalsIgnoreCase(localActiveMode))
            {
                System.out.println("------>   ftp主动模式");
                ftp.enterLocalActiveMode();
            }
            else {
                System.out.println("------>   ftp被动模式");
                ftp.enterLocalPassiveMode();
            }
            //登录
            //设置上传路径

            //指定上传文件的类型  二进制文件
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //读取本地文件
            File file = new File(filepath+fileName);


            local = new FileInputStream(file);
            //第一个参数是文件名
            ftp.storeFile(file.getName(), local);


        } catch (SocketException e) {
            failedFileList.add(fileName);
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            System.out.println(time+"\t-->  发送文件失败："+fileName);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭文件流
                local.close();
                //退出
                ftp.logout();
                //断开连接
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
